package com.atguigu.book.service.impl;

import com.atguigu.book.dao.OrderDAO;
import com.atguigu.book.dao.OrderItemDAO;
import com.atguigu.book.pojo.*;
import com.atguigu.book.service.CartItemService;
import com.atguigu.book.service.OrderService;

import java.util.Collection;
import java.util.List;

/**
 * @ClassName: OrderServiceImpl
 * @Description:
 * @Author: wty
 * @Date: 2022/12/13
 */

public class OrderServiceImpl implements OrderService {
    private OrderDAO orderDAO;
    private OrderItemDAO orderItemDAO;
    private CartItemService cartItemService;

    /**
     * 5. 结账
     * 1) 订单表添加一条记录
     * 2) 订单详情表添加7条记录
     * 3) 购物车项表中需要删除对应的7条记录
     *
     * @param order
     */
    @Override
    public void addOrder(Order order) {
        // 执行完这一步，order中的id是有值的
        // 订单表添加一条记录
        orderDAO.addOrder(order);
        // 这里orderItemList是空的，这里我们应该根据用户的购物车的购物车项，去转换成一个一个的订单项
        User orderUser = order.getOrderUser();
        Cart cart = orderUser.getCart();

        Collection<CartItem> values = cart.getMap().values();
        for (CartItem cartItem : values) {
            OrderItem orderItem = new OrderItem();
            orderItem.setBook(cartItem.getBook());
            orderItem.setBuyCount(cartItem.getBuyCount());
            orderItem.setOrderBean(order);
            // 订单详情表添加x条记录
            orderItemDAO.addOrderItem(orderItem);
        }

        for (CartItem cartItem : values) {
            cartItemService.delCartItem(cartItem);
        }


    }

    @Override
    public List<Order> getOrderList(User user) {
        List<Order> orderList = orderDAO.getOrderList(user);

        for (Order order : orderList) {
            Integer totalBookeCount = orderDAO.getOrderTotalBookeCount(order);
            order.setTotalBookeCount(totalBookeCount);
        }

        return orderList;
    }
}
